import requests
import mutagen
import json
import os

DOWNLOAD_PATH = "C:/Users/XYe/Downloads"

def download_song(title, way="kugou"):
    headers = {
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30",
        "Referer":"http://wedlaa.com/",
        "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
        "Accept":"application/json, text/javascript, */*; q=0.01",
        "Accept-Encoding":"gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Connection":"keep-alive",
        "Host":"mp3.wedlaa.com",
        "Cookie": "PHPSESSID=j9pp520bv5prvbaj6711n3m327",
        "X-Requested-With":"XMLHttpRequest",
        "Content-Length": "84",
        "Origin":"http://wedlaa.com",
        "Accept-Language":"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"
    }
    data = {
        "c":"music",
        "a":"song",
        "key":title,
        "filter":"name",
        "type":way,
        "page":1
    }
    r = requests.post("http://mp3.wedlaa.com/index.php", headers=headers, data=data)
    print(r.content.decode("utf-8"))
    d = json.loads(r.content.decode("utf-8"))
    if d["code"] != 200:
        print(d["error"])
        return False
    for i in d["data"]:
        if title == f"{i['title']}{i['author']}":
            rr = requests.get(i['url'])
            file_name = f"{i['title']} - {i['author']}.mp3"
            with open(os.path.join(DOWNLOAD_PATH, file_name), "wb") as f_obj:
                f_obj.write(rr.content)
            print(f"从{way}下载了{i['title']} - {i['author']}.mp3")
            return True

def modify_info(file_path, title, author, album="", pic_path=""):
    f_obj = mutagen.File(file_path)
    f_obj["TIT2"] = mutagen.id3.TIT2(encoding=3, text=title)
    f_obj["TPE1"] = mutagen.id3.TPE1(encoding=3, text=author)
    if album:
        f_obj["TALB"] = mutagen.id3.TALB(encoding=3, text=album)
    if pic_path:
        with open(pic_path, "rb") as f:
            f_obj["APIC"] = mutagen.id3.APIC(encoding=3, mime="image/jpeg", type=3, data=f.read())
    f_obj.save()
    print("修改了", os.path.split(file_path)[1])

def get_album_info(album_id):
    r = requests.get(f"https://api.imjad.cn/cloudmusic/?type=album&id={album_id}", verify=False)
    data = json.loads(r.content.decode("utf-8"))
    return {
        "artist": data["album"]["artist"]["name"],
        "album": data["album"]["name"],
        "pic": data["album"]["picUrl"],
        "songs": [i["name"] for i in data["songs"]]
    }
    
def download_album(album_id, way="netease"):
    album_info = get_album_info(album_id)
    for song in  album_info["songs"]:
        download_song(song+album_info["artist"], way)
    pic_data = requests.get(album_info['pic'], verify=False)
    file_name = "pic." + album_info['pic'].split(".")[-1]
    pic_path = os.path.join(DOWNLOAD_PATH, file_name)
    with open(pic_path, "wb") as f_obj:
        f_obj.write(pic_data.content)
    for song in album_info["songs"]:
        song_name = f"{song} - {album_info['artist']}.mp3"
        song_path = os.path.join(DOWNLOAD_PATH, song_name)
        if os.path.exists(song_path):
            modify_info(song_path, song, album_info['artist'], album_info['album'], pic_path)
    os.remove(pic_path)
    
def modify_album(album_id):
    info = get_album_info(album_id)
    pic_path = r"C:\Users\XYe\Downloads\1.jpg"
    pic_data = requests.get(info['pic'], verify=False)
    with open(pic_path, "wb") as f_obj:
        f_obj.write(pic_data.content)
    for song in info["songs"]:
        file_path = r"C:\Users\XYe\Downloads"
        file_name = f"{song} - {info['artist']}.mp3"
        try:
            modify_info(os.path.join(file_path, file_name), song, info['artist'], info['album'], pic_path)
        except Exception:
            print(f"失败了:{song} - {info['artist']}.mp3")

def get_song_info(song_id):
    r = requests.get(f"https://api.imjad.cn/cloudmusic/?type=detail&id={song_id}", verify=False)
    data = json.loads(r.content.decode("utf-8"))
    return {
        "title": data["songs"][0]["name"].strip(),
        "album": data["songs"][0]["al"]["name"].strip(),
        "pic": data["songs"][0]["al"]["picUrl"],
        "artist": data["songs"][0]["ar"][0]["name"].strip()
    }

def modify_song(song_id):
    info = get_song_info(song_id)
    pic_path = r"C:\Users\XYe\Downloads\1.jpg"
    pic_data = requests.get(info['pic'], verify=False)
    with open(pic_path, "wb") as f_obj:
        f_obj.write(pic_data.content)
    file_path = r"C:\Users\XYe\Downloads"
    file_name = f"{info['title']} - {info['artist']}.mp3"
    try:
        modify_info(os.path.join(file_path, file_name), info['title'], info['artist'], info['album'], pic_path)
    except Exception:
        print(f"失败了:{file_name}")

def download_a_song(song_id, way):
    info = get_song_info(song_id)
    download_song(info["title"]+info["artist"], way)
    pic_path = r"C:\Users\XYe\Downloads\1.jpg"
    pic_data = requests.get(info['pic'], verify=False)
    with open(pic_path, "wb") as f_obj:
        f_obj.write(pic_data.content)
    file_path = r"C:\Users\XYe\Downloads"
    file_name = f"{info['title']} - {info['artist']}.mp3"
    try:
        modify_info(os.path.join(file_path, file_name), info['title'], info['artist'], info['album'], pic_path)
    except Exception:
        print(f"失败了:{file_name}")
    
def info_full():
    path = r"C:\Users\XYe\Downloads"
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path, file)) and " - " not in file and file.split(".")[-1] == "mp3":
            f = mutagen.File(os.path.join(path, file))
            title = f.tags["TIT2"].text[0]
            author = f.tags["TPE1"].text[0]
            new = f"{title} - {author}.mp3"
            os.rename(os.path.join(path, file), os.path.join(path, new))
            print("修改了", new)
            

# kugou netease kuwo xiami baidu migu

##download_song("没离开过林志炫", "netease")
modify_info(r"C:\Users\XYe\Downloads\新建文件夹\给我一个理由忘记 - 黄丽玲.mp3", "给我一个理由忘记", "黄丽玲", "寂寞不痛", r"C:\Users\XYe\Downloads\1.jpg")
##download_album(28520, "kugou")
##print(get_album_info(3041121))
##modify_album(3041121)
##modify_song(185113)
##download_a_song(109714, "netease")
##info_full()
